
'''
   -*- coding  : ISO-8859-1 -*-
   Description : Clean directories
   History     : 15/05/2008 Initial release
   Author      : M-KPI
'''

import os
import sys
import re
from fnmatch import fnmatch
from traceback import print_exc
from shutil import rmtree

class Cleaner(object):
    def __init__(self, target, wipeList, options):
        self.target = target
        self.wipeList = wipeList
        
        self.test = False
        self.dirs = True
        self.files = True
        self.verbose = True
        
        for option in options:
            self.__setattr__(option , options[option])
            
        if not self.dirs and not self.files:
            print 'No files to process'
            sys.exit(0)
        
        self.printP()
        
    def p(self, message):
        if self.verbose:
            print message
            
    def delete(self, path):
        self.p('try to remove\t: %s'%path)
        if self.test:
            return True
        if os.path.isfile(path):
            try:
                os.unlink(path)
            except:
                self.p('not removed')
                print_exc()
        else:
            try:
                rmtree(path)
            except:
                self.p('not removed')
                print_exc()
                
    def check(self, name):
        for case in self.wipeList:
            if fnmatch(name, case):
                return True
        return False
    
    def printP(self):
        if self.test:
            print 'Run in test mode...'
        
        if not self.files:
            self.p('We not process files')
        elif not self.dirs:
            self.p('We not process directories')
        else:
            self.p('We process files and directiories')
            
        
            
            
    def clean(self):
        for root, dirs, files in os.walk(self.target):
            if self.dirs:
                for dir in dirs:
                    target = os.path.join(root, dir)
                    if self.check(dir):
                        self.delete(target)
            if self.files:
                for file_ in files:
                    target = os.path.join(root, file_)
                    if self.check(file_):
                        self.delete(target)
                

def main():
    if '-h' == sys.argv[1]:
        print '''usage: cleaner TARGET [options] [WIPELIST]
        -h : show this help
        -s : silent mode
        -dm : directory mode
        -fm : file mode
        -am : all mode (default)
        -tm : test mode'''
        sys.exit(0)
        
    if not os.path.exists(sys.argv[1]):
        print 'Couldn\'t find directory : %s'%sys.argv[1]
        sys.exit(0)
        
    target = sys.argv[1]
    opts = {}
    args = sys.argv
    if '-s' in args:
        opts['verbose'] = False
    if '-dm' in args:
        opts['files'] = False
    if '-fm' in args:
        opts['dirs'] = False
#    if '-rx' in args:
#        opts['regexp'] = True
    if '-tm' in args:
        opts['test'] = True
        
    wipeList = []
    for element in sys.argv[1:]:
        if element.startswith('-'):
            continue
        wipeList.append(element)
        
    cleaner = Cleaner(target, wipeList, opts)
    cleaner.clean()
        
        
        

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print 'You should define target directory. -h for help'
    else:
        main()
        
        